package com.jianggujin.redis.component;

import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;

public class MainMenuBar extends JMenuBar {
    // 菜单栏
    private JMenu fileMenu;
    private JMenuItem openConnectMenuItem;
    private JMenuItem quitMenuItem;
    private JMenu helpMenu;
    private JMenuItem reportBugMenuItem;
    private JMenuItem aboutMenuItem;
    private MainMenuListener listener = null;
    private ActionListener actionListener = e -> {
        if (listener == null) {
            return;
        }
        Object source = e.getSource();
        if (openConnectMenuItem == source) {
            listener.handleOpenConnect();
        } else if (quitMenuItem == source) {
            listener.handleQuitApplication();
        } else if (reportBugMenuItem == source) {
            listener.handleReportBug();
        } else if (aboutMenuItem == source) {
            listener.handleShowAbout();
        }
    };

    public MainMenuBar() {
        fileMenu = new JMenu("File");
        fileMenu.setMnemonic('F');

        openConnectMenuItem = new JMenuItem("Connect...");
        openConnectMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
        openConnectMenuItem.addActionListener(actionListener);

        quitMenuItem = new JMenuItem("Exit...");
        quitMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_MASK));
        quitMenuItem.addActionListener(actionListener);

        fileMenu.add(openConnectMenuItem);
        fileMenu.add(quitMenuItem);

        helpMenu = new JMenu("Help");
        helpMenu.setMnemonic('H');

        reportBugMenuItem = new JMenuItem("Report Bug...");
        reportBugMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_MASK));
        reportBugMenuItem.addActionListener(actionListener);

        aboutMenuItem = new JMenuItem("About...");
        aboutMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK));
        aboutMenuItem.addActionListener(actionListener);

        helpMenu.add(reportBugMenuItem);
        helpMenu.add(aboutMenuItem);

        this.add(fileMenu);
        this.add(helpMenu);
    }

    public void setMainMenuListener(MainMenuListener listener) {
        this.listener = listener;
    }

    public static interface MainMenuListener {

        void handleOpenConnect();

        void handleShowAbout();

        void handleReportBug();

        void handleQuitApplication();
    }
}
